﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using Kugar.Core.BaseStruct;
using Kugar.Core.Configuration;
using Kugar.Core.ExtMethod;
using Kugar.Core.SystemManager;
using Microsoft.Owin;
using Microsoft.Owin.Hosting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Owin;

namespace Kugar.Tool.DataSync.Server.OWin
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Contains("-service", StringComparer.CurrentCultureIgnoreCase))
            {
                SystemManager.InstallService("KugarDataSyncServer",Path.GetFullPath(System.Environment.CommandLine));
                SystemManager.StartService("KugarDataSyncServer");
                //registerService();
                return;
            }
            


            int port = CustomConfigManager.Default.AppSettings.GetValueByName("HttpPort", "9091").ToInt();

            var webApp = WebApp.Start<Startup>(new StartOptions()
            {
                Port = port
            });

            new ImportController();

            Console.WriteLine("已开始监听");

            Console.ReadLine();

            webApp.Dispose();
            
        }
    }

    public class ImportController : ApiController
    {
        private static DataSyncServer _dataSync = null;

        static ImportController()
        {
            _dataSync=new DataSyncServer();
            var agg = new AggregateCatalog();
            agg.Catalogs.Add(new DirectoryCatalog(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"plugins"),"*.dll"));
            agg.Catalogs.Add(new AssemblyCatalog(typeof(Program).Assembly));
            
            _dataSync.Initialize(agg);
        }

        public async Task<ResultReturn> Update(string appID, string dataType)
        {
            var jsonStr = await Request.Content.ReadAsStringAsync();

            var importJson = JsonConvert.DeserializeObject<JObject>(jsonStr);

            return _dataSync.TriggerImport(appID, dataType, importJson);
        }
    }

    public class Startup
    {
        public void Configuration(IAppBuilder appBuilder)
        {
            // Configure Web API for self-host. 
            HttpConfiguration config = new HttpConfiguration();

            var pluginPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "plugins");

            if (!Directory.Exists(pluginPath))
            {
                Directory.CreateDirectory(pluginPath);
            }

            //config.Filters.Add(new GlobalFilterAttribute());
            
            config.Routes.MapHttpRoute(
                name: "ClientDefaultApi",
                routeTemplate: "Import/{appid}/{dataType}",
                defaults: new { controller = "Import", action = "Update" }
            );

            
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "{controller}/{action}",
                defaults: new { controller = "home", action = "index" }
            );

            appBuilder.UseWebApi(config);

            var asse = typeof(Program).Assembly.GetReferencedAssemblies().ToArray();

            foreach (var assembly in asse)
            {
                AppDomain.CurrentDomain.Load(assembly);
            }

            //config.Services.Replace(typeof(IHttpControllerSelector),new MefControllerSelector(config));
            // config.Services.Replace(typeof(IHttpControllerTypeResolver),new MefHttpControllerTypeResolver());

        }

        private async Task onRun(IOwinContext context)
        {
            Console.WriteLine(context.Request.Uri.ToString());
        }
    }
}
